<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/blog/","images":"/blog/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/blog/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="记录在学习设计模式过程中的点滴">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式学习记录">
<meta property="og:url" content="http://littlefxc.github.io/2021/02/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="记录在学习设计模式过程中的点滴">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/fbc5b62b7710fe70d99ab45f7cc8b53d.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/443fc2b10d2bc790bbe6aee06eea25a1.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/001bf164def93d6de76d1edfca33844f.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F-0.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/%E6%A1%A5%E6%8E%A5%E6%A8%A1%E5%BC%8F.png">
<meta property="article:published_time" content="2021-02-24T01:11:19.000Z">
<meta property="article:modified_time" content="2021-04-01T05:23:10.000Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/fbc5b62b7710fe70d99ab45f7cc8b53d.png">


<link rel="canonical" href="http://littlefxc.github.io/2021/02/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>设计模式学习记录 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/blog/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/blog/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/blog/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/blog/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/blog/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text">1 单例模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-%E9%A5%BF%E6%B1%89%E5%BC%8F%E6%A0%87%E5%87%86%E5%86%99%E6%B3%95"><span class="nav-text">1.1 饿汉式标准写法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-%E9%A5%BF%E6%B1%89%E5%BC%8F%E9%9D%99%E6%80%81%E5%9D%97%E6%9C%BA%E5%88%B6%E5%86%99%E6%B3%95"><span class="nav-text">1.2 饿汉式静态块机制写法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3-%E6%87%92%E6%B1%89%E5%BC%8F%E5%8D%95%E4%BE%8B%E5%86%99%E6%B3%95"><span class="nav-text">1.3 懒汉式单例写法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-4-synchronized%E4%BF%AE%E9%A5%B0%E7%9A%84%E6%87%92%E6%B1%89%E5%BC%8F%E5%8D%95%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text">1.4 synchronized修饰的懒汉式单例实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-5-%E6%87%92%E6%B1%89%E5%BC%8F-%E5%8F%8C%E9%87%8D%E6%A3%80%E6%B5%8B%E5%8D%95%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text">1.5 懒汉式-双重检测单例实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-6-%E9%9D%99%E6%80%81%E5%86%85%E9%83%A8%E7%B1%BB%E5%8D%95%E4%BE%8B%E5%AE%9E%E7%8E%B0"><span class="nav-text">1.6 静态内部类单例实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-%E5%88%9B%E5%BB%BA%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text">2 创建者模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F"><span class="nav-text">2.1 工厂方法模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F"><span class="nav-text">2.2 抽象工厂方法模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text">2.3 建造者模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-4-%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text">2.4 原型模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-%E7%BB%93%E6%9E%84%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text">3 结构型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F"><span class="nav-text">3.1 适配器模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-%E6%A1%A5%E6%8E%A5%E6%A8%A1%E5%BC%8F"><span class="nav-text">3.2 桥接模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%BA%90"><span class="nav-text">参考资源</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">184</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">35</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">115</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/02/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          设计模式学习记录
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-02-24 09:11:19" itemprop="dateCreated datePublished" datetime="2021-02-24T09:11:19+08:00">2021-02-24</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-04-01 13:23:10" itemprop="dateModified" datetime="2021-04-01T13:23:10+08:00">2021-04-01</time>
      </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>记录在学习设计模式过程中的点滴</p>
<span id="more"></span>

<h1 id="1-单例模式"><a href="#1-单例模式" class="headerlink" title="1 单例模式"></a>1 单例模式</h1><ul>
<li><p>优点：</p>
<ul>
<li>单例模式可以保证内存中只有一个实例对象，从而会减少内存的开销；</li>
<li>单例模式可以避免对资源的多重占用；</li>
<li>单例模式设置全局访问点，可以起到优化和共享资源的访问的作用；</li>
</ul>
</li>
<li><p>缺点：</p>
<ul>
<li><strong>扩展难</strong>， 因为单例模式通常是没有接口的啊，如果想要扩展，那么你唯一途径就是修改之前的代码，所以说单例模式违背了开闭原则；</li>
<li><strong>调试难</strong>，因为在并发测试中，单例模式是不利于代码的调试的，单例中的代码没有执行完，也不能模拟生成一个新对象；</li>
<li><strong>违背单一职责原则</strong>，因为单例模式的业务代码通常写在一个类中，如果功能设计不合理，就很容易违背单一职责原则；</li>
</ul>
</li>
</ul>
<h2 id="1-1-饿汉式标准写法"><a href="#1-1-饿汉式标准写法" class="headerlink" title="1.1 饿汉式标准写法"></a>1.1 饿汉式标准写法</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 单例模式的通用写法</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 内部初始化一次</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Singleton instance = <span class="keyword">new</span> Singleton();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 隐藏构造方法</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 提供一个全局访问点</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> Singleton</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>饿汉式单例写法在类的初始化的时候就会进行初始化操作，并且创建对象，绝对的线程安全，因为此时线程还没有出现就已经实例化了，故不会存在访问安全的问题。</p>
<h2 id="1-2-饿汉式静态块机制写法"><a href="#1-2-饿汉式静态块机制写法" class="headerlink" title="1.2 饿汉式静态块机制写法"></a>1.2 饿汉式静态块机制写法</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HungryStaticSingleton</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> HungryStaticSingleton hungrySingleton;</span><br><span class="line">    <span class="comment">//静态代码块 类加载的时候就初始化</span></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        hungrySingleton=<span class="keyword">new</span> HungryStaticSingleton();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 私有化构造函数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">HungryStaticSingleton</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 提供一个全局访问点</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> HungryStaticSingleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> hungrySingleton;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这种写法可以明显的看到所以对象是类在加载的时候就进行实例化了，那么这样一来，会导致单例对象的数量不确定，从而会导致系统初始化的时候就造成大量内存浪费。</p>
<h2 id="1-3-懒汉式单例写法"><a href="#1-3-懒汉式单例写法" class="headerlink" title="1.3 懒汉式单例写法"></a>1.3 懒汉式单例写法</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LazySimpleSingleton</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> LazySimpleSingleton lazySingleton = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 私有化构造函数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">LazySimpleSingleton</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 提供一个全局访问点</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> LazySimpleSingleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (lazySingleton == <span class="keyword">null</span>) &#123;</span><br><span class="line">            lazySingleton = <span class="keyword">new</span> LazySimpleSingleton();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> lazySingleton;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> 这样实现的好处就是只有对象被使用的时候才会进行初始化，不会存在内存浪费的问题，但是它会在多线程环境下，存在线程安全问题。</p>
<h2 id="1-4-synchronized修饰的懒汉式单例实现"><a href="#1-4-synchronized修饰的懒汉式单例实现" class="headerlink" title="1.4 synchronized修饰的懒汉式单例实现"></a>1.4 synchronized修饰的懒汉式单例实现</h2><p>我们可以利用<code>synchronized</code>关键字将全局访问点方法变成一个同步方法，这样就可以解决线程安全的问题，代码如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LazySimpleSingleton</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> LazySimpleSingleton lazySingleton = <span class="keyword">null</span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 私有化构造函数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">LazySimpleSingleton</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 提供一个全局访问点  </span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">static</span>  LazySimpleSingleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (lazySingleton == <span class="keyword">null</span>) &#123;</span><br><span class="line">            lazySingleton = <span class="keyword">new</span> LazySimpleSingleton();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> lazySingleton;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> 但是，这样虽然解决了线程安全的问题，可是如果在线程数量剧增的情况下，用<code>synchronized</code>加锁，则会导致大批线程阻塞，从而骤减系统性能。</p>
<h2 id="1-5-懒汉式-双重检测单例实现"><a href="#1-5-懒汉式-双重检测单例实现" class="headerlink" title="1.5 懒汉式-双重检测单例实现"></a>1.5 懒汉式-双重检测单例实现</h2><p>在上述代码上进一步优化，代码如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LazyDoubleCheckSingleton</span> </span>&#123;</span><br><span class="line">    <span class="comment">// volatile 关键字修饰</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">static</span> LazyDoubleCheckSingleton lazySingleton ;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 私有化构造函数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">LazyDoubleCheckSingleton</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 提供一个全局访问点</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> LazyDoubleCheckSingleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 这里先判断一下是否阻塞</span></span><br><span class="line">        <span class="keyword">if</span> (lazySingleton == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (LazyDoubleCheckSingleton.class)&#123;</span><br><span class="line">                <span class="comment">// 判断是否需要重新创建实例</span></span><br><span class="line">                <span class="keyword">if</span> (lazySingleton == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    lazySingleton = <span class="keyword">new</span> LazyDoubleCheckSingleton();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> lazySingleton;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当第一个线程调用<code>getInstance()</code>方法时，第二个线程也可以调用，但是第一个线程执行<code>synchronized</code>时候，第二个线程就会发现阻塞，但是此时的阻塞是<code>getInstance()</code>内部的阻塞。</p>
<h2 id="1-6-静态内部类单例实现"><a href="#1-6-静态内部类单例实现" class="headerlink" title="1.6 静态内部类单例实现"></a>1.6 静态内部类单例实现</h2><p>虽然双重检测锁的单例模式解决了线程安全和性能问题，但是毕竟涉及加锁的操作，多多少少就会到了性能的影响，下面我们分享一下更加优雅的单例模式实现，如下代码所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LazyStaticInnerClassSingleton</span> </span>&#123;</span><br><span class="line">    <span class="comment">//  在构造方法里面抛出异常真的合适？</span></span><br><span class="line">  <span class="function"><span class="keyword">private</span> <span class="title">LazyStaticInnerClassSingleton</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(LazyHolder.INSTANCE != <span class="keyword">null</span>)&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">&quot;不允许创建多个实例&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// static 保证这个方法不会被重写 覆盖</span></span><br><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> LazyStaticInnerClassSingleton <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> LazyHolder.INSTANCE;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Java 默认不会加载内部类</span></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">LazyHolder</span></span>&#123;</span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> LazyStaticInnerClassSingleton INSTANCE=<span class="keyword">new</span> LazyStaticInnerClassSingleton();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="2-创建者模式"><a href="#2-创建者模式" class="headerlink" title="2 创建者模式"></a>2 创建者模式</h1><h2 id="2-1-工厂方法模式"><a href="#2-1-工厂方法模式" class="headerlink" title="2.1 工厂方法模式"></a>2.1 工厂方法模式</h2><p>工厂模式又称工厂方法模式，是一种创建者模式，主要是在父类中提供一个创建对象的方法，允许子类决定实例化对象的类型。</p>
<p>这种设计模式也是 Java 开发中最常见的一种模式，它的主要意图是定义一个创建对象的接口，让其子类自己决定实例化哪一个工厂类，工厂模式使其创建过程延迟到子类进行。</p>
<p>简单来说，就是为了提供代码结构的扩展性，屏蔽每一个功能类中的具体实现逻辑。让外部可以更简单的只是知道调用即可，同时这也是去掉众多 ifelse 的方式。当然这也可能有一些缺点，比如需要实现的类非常多，如何去维护，怎样去降低成本。但这些问题都可以在后续的设计模式结合使用中，逐步降低。</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/fbc5b62b7710fe70d99ab45f7cc8b53d.png" alt="https://gitee.com/littlefxc/oss/raw/master/images/工厂模式类图.png"></p>
<h2 id="2-2-抽象工厂方法模式"><a href="#2-2-抽象工厂方法模式" class="headerlink" title="2.2 抽象工厂方法模式"></a>2.2 抽象工厂方法模式</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/443fc2b10d2bc790bbe6aee06eea25a1.png" alt="https://gitee.com/littlefxc/oss/raw/master/images/抽象工厂模式.png"></p>
<h2 id="2-3-建造者模式"><a href="#2-3-建造者模式" class="headerlink" title="2.3 建造者模式"></a>2.3 建造者模式</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/001bf164def93d6de76d1edfca33844f.png" alt="https://gitee.com/littlefxc/oss/raw/master/images/建造者模式.png"></p>
<h2 id="2-4-原型模式"><a href="#2-4-原型模式" class="headerlink" title="2.4 原型模式"></a>2.4 原型模式</h2><p>原型模式主要解决的是创建重复对象，而这部分对象内容本身比较复杂，生成过程可能从库或者RPC接口中获取数据的耗时较长，因此采用克隆的方式节省时间。</p>
<p>案例场景：在线生成试卷，考题从题库中抽选随机成立一份试卷，考题类型有选择题、问答题</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F-0.png" alt="https://gitee.com/littlefxc/oss/raw/master/images/原型模式-0.png"></p>
<h1 id="3-结构型模式"><a href="#3-结构型模式" class="headerlink" title="3 结构型模式"></a>3 结构型模式</h1><h2 id="3-1-适配器模式"><a href="#3-1-适配器模式" class="headerlink" title="3.1 适配器模式"></a>3.1 适配器模式</h2><blockquote>
<p>本示例来自于<a target="_blank" rel="noopener" href="https://www.runoob.com/design-pattern/adapter-pattern.html">https://www.runoob.com/design-pattern/adapter-pattern.html</a></p>
</blockquote>
<p>适配器模式(Adapter Pattern) ：将一个接口转换成客户希望的另一个接口，适配器模式使接口不兼容的那些类可以一起工作，其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式，也可以作为对象结构型模式。</p>
<p>适配器模式包含如下角色：</p>
<ul>
<li>Target：目标抽象类</li>
<li>Adapter：适配器类</li>
<li>Adaptee：适配者类</li>
<li>Client：客户类</li>
</ul>
<p>案例场景：音频播放器设备只能播放 mp3 文件，通过使用一个更高级的音频播放器来播放 vlc 和 mp4 文件。</p>
<p>实现思路：我们想要让 <em>AudioPlayer</em> 播放其他格式的音频文件。为了实现这个功能，我们需要创建一个实现了 <em>MediaPlayer</em> 接口的适配器类 <em>MediaAdapter</em>，并使用 <em>AdvancedMediaPlayer</em> 对象来播放所需的格式。</p>
<p>类图如下：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F.png" alt="适配器模式"></p>
<h2 id="3-2-桥接模式"><a href="#3-2-桥接模式" class="headerlink" title="3.2 桥接模式"></a>3.2 桥接模式</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/%E6%A1%A5%E6%8E%A5%E6%A8%A1%E5%BC%8F.png" alt="桥接模式"></p>
<h1 id="参考资源"><a href="#参考资源" class="headerlink" title="参考资源"></a>参考资源</h1><ul>
<li><p><a target="_blank" rel="noopener" href="https://msjavacoder.github.io/msJava/#/docs/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F">https://msjavacoder.github.io/msJava/#/docs/设计模式/单例模式</a></p>
</li>
<li><p>《重学Java设计模式·小傅哥》</p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://www.runoob.com/design-pattern/adapter-pattern.html">https://www.runoob.com/design-pattern/adapter-pattern.html</a></p>
</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag"># 设计模式</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/blog/2021/02/23/JVM-%E8%B0%83%E4%BC%98/" rel="prev" title="JVM 调优">
                  <i class="fa fa-chevron-left"></i> JVM 调优
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/blog/2021/03/22/Java%E5%A4%9A%E7%BA%BF%E7%A8%8BJUC%E9%94%81-%E7%AE%80%E4%BB%8B/" rel="next" title="Java多线程JUC锁-简介">
                  Java多线程JUC锁-简介 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/blog/js/utils.js"></script><script src="/blog/js/motion.js"></script><script src="/blog/js/schemes/muse.js"></script><script src="/blog/js/next-boot.js"></script>

  
<script src="/blog/js/local-search.js"></script>






  





</body>
</html>
